<template>
  <el-dialog title="选择规格" v-model="visible" width="40%" :close-on-click-modal="false" :close-on-press-escape="false" :show-message="false">
    <div class="goods-detail">
      <div class="goods">
        <img :src="goodsData.goodsDetail.goodsImg?.split(',')[0]" alt="" />
        <div>
          <p class="goods-name">{{ goodsData.goodsDetail.goodsName }}</p>
          <p class="goodsTitle">{{ goodsData.goodsDetail.goodsSubtitle }}</p>
        </div>
      </div>

      <div class="goods-price">
        <span class="goods-title">售价</span>
        <span class="goods-content">￥</span>
        <span class="goods-price-value"> {{ goodsData.goodsDetail.goodsSalesPrice }}</span>
      </div>
      <div style="margin: 20px 0 0 10px">
        <div class="goods-factory" v-if="goodsData.goodsDetail.factoryName">
          <span class="goods-title">厂家</span>
          <span class="goods-content">{{ goodsData.goodsDetail.factoryName }}</span>
        </div>

        <div class="goods-spec">
          <template v-for="item in goodsData.goodsDetail.goodsExpandparamValueList" :key="item.expandparamValueId">
            <div class="expand">
              <span class="goods-title">{{ item.expandparamName }}</span>
              <span class="goods-content">{{ item.expandparamValueName }}</span>
            </div>
          </template>
        </div>
        <div class="goods-num">
          <span class="goods-title">数量</span>
          <el-input-number class="goods-content" size="small"  v-model="goodsData.form.amount" @change="onAmountChange"/>
        </div>

        <div class="goods-btn">
          <Button v-if="goodsData.goodsDetail.salesFlag === 'NO'" class="goods-disable-buy" disabled label="暂无购买权限" />

          <div v-else class="goods-confirm">
            <Button class="goods-buy" label="立即购买" @click="onCartPurchaseClick" :disabled="goodsData.goodsDetail.stock === 0 || goodsData.goodsDetail.salesFlag === 'NO'" />
            <Button class="goods-add" label="加入购物车" :style="{ background: goodsData.currSpec.stock === 0 || goodsData.goodsDetail.salesFlag === 'NO' ? '#ccc' : '#e89000' }" :disabled="goodsData.goodsDetail.stock === 0 || goodsData.goodsDetail.salesFlag === 'NO'" @click="onAddCartClick" />
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { reactive, computed, toRefs, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import api from '@/api'
import { cartStore } from '@/store/cart'
import Button from '@/components/button/button.vue'

const router = useRouter()
const _cartStore = cartStore()

const props = defineProps(['visible', 'goodsId'])
const emit = defineEmits(['update:visible'])

const visible = computed({
  get: () => {
    return props.visible
  },
  set: (value) => emit('update:visible', value)
})

watch(
  () => props.goodsId,
  (val) => {
    if (val) {
      loadData()
    }
  }
)

const goodsData = reactive({
  goodsDetail: {},
  currSpec: {},
  form: {
    amount: 1,
    goodsSpec: '',
    goodsSpecId: '',
    price: '',
    goodsCategoryName: '',
    stock: ''
  }
})

const customerId = localStorage.getItem('_site_login_userId')

const addCart = async () => {
  if (goodsData.form.amount < goodsData.goodsDetail.minimumQuantity) {
    ElMessage.error(`此商品起订量为${goodsData.goodsDetail.minimumQuantity}，请重新输入商品数量`);
    nextTick(() => {
      goodsData.form.amount = goodsData.goodsDetail.minimumQuantity;
    })
    return
  }
  let { factoryName, goodsDesc, goodsId, goodsImg, goodsName, goodsSubtitle, supplierId, unit, goodsSalesPrice, goodsCatNameFirst, goodsCatNameSecond } = goodsData.goodsDetail
  goodsData.form.price = goodsSalesPrice
  goodsData.form.goodsCategoryName = `${goodsCatNameFirst}-${goodsCatNameSecond}`

  goodsData.form = Object.assign(goodsData.form, { factoryName, goodsDesc, goodsId, goodsImg, goodsName, goodsSubtitle, supplierId, unit })

  goodsData.form.goodsImg = goodsImg?.split(',')[0]

  let { err } = await api.post(`/medinstrument/site/cart/addCart`, goodsData.form)
  if (err) {
    ElMessage.error(err)
  } else {
    ElMessage.success('商品添加成功')
    _cartStore.add(goodsId)
    visible.value = false
  }
}

const loadData = async () => {
  let { data, err } = await api.get(`/medinstrument/site/goods/goodsDetail?goodsId=${props.goodsId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    goodsData.goodsDetail = data.goodsVo
    goodsData.form.amount = goodsData.goodsDetail.minimumQuantity
  }
}

const onCartPurchaseClick = () => {
  if (goodsData.form.amount < goodsData.goodsDetail.minimumQuantity) {
    ElMessage.error(`此商品起订量为${goodsData.goodsDetail.minimumQuantity}，请重新输入商品数量`);
    nextTick(() => {
      goodsData.form.amount = goodsData.goodsDetail.minimumQuantity;
    })
    return
  }
  router.push({ path: '/settlement', query: { amount: goodsData.form.amount, goodsId: goodsData.goodsDetail.goodsId } })
}

const onAmountChange = (val) => {
  if (goodsData.form.amount < goodsData.goodsDetail.minimumQuantity) {
    ElMessage.error(`此商品起订量为${goodsData.goodsDetail.minimumQuantity}，请重新输入商品数量`);
  }
}

const onAddCartClick = () => {
  addCart()
}
</script>
<style scoped lang="scss">
.goods-detail {
  padding: 0 20px;

  .goods {
    display: flex;
    margin-bottom: 20px;

    img {
      width: 92px;
      height: 92px;
      margin-right: 20px;
    }

    .goods-name {
      font-size: 16px;
      line-height: 22px;
      font-weight: 500;
    }

    .goodsTitle {
      line-height: 20px;
      color: var(--color-primary);
      margin-top: 8px;
    }
  }

  .goods-price,
  .goods-spec,
  .goods-num,
  .goods-brand,
  .goods-factory,
  .goods-cate {
    margin-bottom: 20px;

    .goods-content {
      margin-left: 30px;
    }
  }

  .goods-factory,
  .goods-cate,
  .goods-title,
  .goods-brand {
    // height: 17px;
    font-size: 12px;
  }

  .goods-title {
    display: inline-block;
    font-size: 12px;
    height: 17px;
    width: 58px;
  }

  .goods-price {
    padding: 14px 0 14px 10px;
    background: var(--color-background);

    .goods-content,
    .goods-price-value {
      color: #c00000;
    }

    .goods-price-value {
      font-weight: 500;
      font-size: 24px;
      line-height: 33px;
    }
  }

  .goods-spec {
    .expand {
      margin-bottom: 20px;
    }

    .expand:last-child {
      margin-bottom: 0;
    }
  }

  .goods-num .el-input-number :deep(.el-input--small) {
    width: 124px;
    height: 34px;
  }

  .el-input-number--small {
    width: 124px;
    height: 32px;

    :deep(.el-input-number__decrease),
    :deep(.el-input-number__increase) {
      width: 32px;
      height: 32px;
      box-sizing: border-box;
    }
  }

  .goods-btn {
    display: flex;
    justify-content: center;
    padding: 0 20px 20px 0;
  }

  :deep(.goods-add) {
    background-color: var(--color-primary);
    border: none;

    span {
      color: #ffffff;
    }
  }

  :deep(.goods-buy) {
    background-color: #fff9ee;
    border: 1px solid var(--color-primary);

    span {
      color: var(--color-primary);
    }
  }

  .goods-confirm {
    margin-right: 12px;
  }
}
</style>
